package com.sxt.sys.realm;

import com.sxt.sys.domain.Operator;
import com.sxt.sys.service.OperatorService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm认证授权管理
 * @author WanMing
 * @date 2019/1/31 10:18
 */

public class OperatorRealm extends AuthorizingRealm {


    @Autowired
    private OperatorService operatorService;


    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Operator operator = (Operator) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //授权存入info
        if(!operator.getIsAdmin().isEmpty()){
            info.addRole(operator.getIsAdmin());
        }
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名和密码的char数组
        String operatorName = authenticationToken.getPrincipal().toString();
        //查询该用户名的用户是否存在
        Operator operator = operatorService.queryOperatorByOperatorName(operatorName);
        if (null != operator) {
            //存在，继续验证密码
            //设置凭证匹配器根据用户名和得知加盐
            ByteSource bytes = ByteSource.Util.bytes(operator.getOperatorName());
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(operator, operator.getOperatorPwd(), bytes, getName());
            return authenticationInfo;
        } else {
            //用户不存在

            return null;
        }

    }
}
